<template>
  <div class="w-full flex justify-between items-center">
    <p class="calendar-title">选择参观日期</p>
    <p class="calendar-month">{{ dateFormat(new Date(), "YYYY.MM") }}</p>
  </div>
  <div class="calendar">
    <ul class="week-ul">
      <li>
        <p>一</p>
        <p>MON</p>
      </li>
      <li>
        <p>二</p>
        <p>TUS</p>
      </li>
      <li>
        <p>三</p>
        <p>WED</p>
      </li>
      <li>
        <p>四</p>
        <p>THU</p>
      </li>
      <li>
        <p>五</p>
        <p>FRI</p>
      </li>
      <li>
        <p>六</p>
        <p>SAT</p>
      </li>
      <li>
        <p>日</p>
        <p>SUN</p>
      </li>
    </ul>
    <ul class="date-ul">
      <li
        v-for="item in calendarDate"
        :key="item.dt"
        @click="setActDate(item)"
        :class="{
          forbid_click: item.status != 2 || item.totalTicketsNum === 0,
          date_act: actDate == item.dt,
        }"
      >
        <p class="p_date">{{ item.dtLabel }}</p>
        <p class="p_status" v-if="!item.status">不可预约</p>
        <p class="p_status" v-else-if="item.status == 1">闭馆</p>
        <p class="p_status" v-else-if="item.status == 3">已约满</p>
        <p class="p_status" v-else-if="item.status == 2 && item.totalTicketsNum === 0">已约满</p>
        <p class="p_status" v-else-if="item.status == 2">{{ item.totalTickets }}</p>
        <span v-if="item.isToday" style="transform: scale(1)">今</span>
      </li>
    </ul>
    <div class="time-box">
      <p>入馆时段：</p>
      <ul>
        <li
          v-for="item in timePeriod"
          :key="item.timePeriod"
          :class="{ 
            time_act: actTimePeriod == item.timePeriod,
            forbid_click: item.ticketNum <= 0 
          }"
          @click="setActTimePeriod(item)"
        >
          <div class="time-item">
            <div>{{ item.timePeriodShow }}</div>
            <div class="ticket-num">余{{ item.ticketNum }}</div>
          </div>
        </li>
      </ul>
    </div>
  </div>
  <div class="tip-info">
    <p>团体参观预约须知：</p>
    <div v-html="noticeReservation"></div>
  </div>
  <div class="bottom-round">
    <div class="bottom-btn fir" @click="router.push('/record')">预约记录</div>
    <div class="bottom-btn sec" @click="onAdd">立即预约</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeMount, toRaw, computed, watch } from "vue";
import { museumCalendar } from "@/request/api/reserve";
import { dateFormat } from "@/utils/dateFormat";
import { useOrderStore } from "@/stores/order";
import { type OrderDTO } from "@/interface/order";
import { showNotify } from "vant";
import router from "@/router";

const calendarDate = ref<Array<any>>([]);
const calendarDataMap = ref<Record<string, any>>({});
const actDate = ref("");
const timePeriod = ref<Array<any>>([]);
const actTimePeriod = ref<null | string>(null);
const order = useOrderStore().orderGetter;
const noticeReservation = computed(() => {
  return useOrderStore().noticeReservation;
});

const getCalendar = () => {
  museumCalendar(2).then((res: any) => {
    if (res.data.length > 0) {
      const arr: any = {};
      
      // 存储完整的日历数据，包括时间段信息
      res.data.forEach((s: any) => {
        arr[s.museumDate] = s;
        calendarDataMap.value[s.museumDate] = s;
      });
      
      const oneDayTime = 24 * 60 * 60 * 1000;
      let firstMondayTime = new Date(
        new Date(res.data[0].museumDate).getTime() -
          ((new Date(res.data[0].museumDate).getDay() || 7) - 1) * oneDayTime
      );
      let lastSundayTime = new Date(
        new Date(res.data[res.data.length - 1].museumDate).getTime() +
          (7 -
            (new Date(res.data[res.data.length - 1].museumDate).getDay() ||
              7)) *
            oneDayTime
      );
      let diff = getDiffDay(firstMondayTime, lastSundayTime);
      let startDate = firstMondayTime.getDate();
      let today = dateFormat(new Date(), "YYYY-MM-DD");
      
      for (let i = 0; i <= diff; i++) {
        let st = new Date(firstMondayTime);
        const dt = st.setDate(startDate + i);
        const formattedDate = dateFormat(dt, "YYYY-MM-DD");
        
        let isToday = false;
        let status = 0;
        let totalTickets = '';
        let totalTicketsNum = 0;
        
        if (arr[formattedDate]) {
          status = arr[formattedDate].status;
          
          // 计算总票数
          if (arr[formattedDate].timePeriodList && arr[formattedDate].timePeriodList.length > 0) {
            totalTicketsNum = arr[formattedDate].timePeriodList.reduce((sum: number, period: any) => {
              return sum + period.ticketNum;
            }, 0);
            totalTickets = totalTicketsNum > 0 ? `余${totalTicketsNum}` : '已约满';
            
            // 如果总票数为0但状态是可预约，将状态更新为已约满
            if (totalTicketsNum === 0 && status === 2) {
              status = 3; // 改为已约满状态
            }
          }
        }
        
        if (formattedDate == today) {
          isToday = true;
        }
        
        calendarDate.value.push({
          dt: formattedDate,
          dtLabel: dateFormat(dt, "D"),
          isToday: isToday,
          status: status,
          totalTickets: totalTickets,
          totalTicketsNum: totalTicketsNum
        });
      }
      
      // 如果有默认选中日期，加载对应的时段信息
      if (actDate.value) {
        loadTimePeriods(actDate.value);
      } else if (res.data.find((item: any) => item.status === 2)) {
        // 如果没有选中日期，选择第一个可预约且有票的日期
        const firstAvailableDate = res.data.find((item: any) => {
          if (item.status === 2) {
            // 检查是否有可用票
            const totalTickets = item.timePeriodList.reduce((sum: number, period: any) => {
              return sum + period.ticketNum;
            }, 0);
            return totalTickets > 0;
          }
          return false;
        });
        
        if (firstAvailableDate) {
          actDate.value = firstAvailableDate.museumDate;
          loadTimePeriods(actDate.value);
        }
      }
    }
  });
};

// 根据选中日期加载时间段
const loadTimePeriods = (date: string) => {
  if (calendarDataMap.value[date] && calendarDataMap.value[date].timePeriodList) {
    timePeriod.value = calendarDataMap.value[date].timePeriodList;
  } else {
    timePeriod.value = [];
  }
  
  // 重置时段选择
  actTimePeriod.value = null;
};

const getDiffDay = (date_1: any, date_2: any) => {
  let totalDays, diffDate;
  let myDate_1 = Date.parse(date_1);
  let myDate_2 = Date.parse(date_2);
  diffDate = Math.abs(myDate_1 - myDate_2);
  totalDays = Math.floor(diffDate / (1000 * 3600 * 24));
  return totalDays;
};

const setActDate = (item: any) => {
  if (item.status == 2 && item.totalTicketsNum > 0) {
    actDate.value = item.dt;
    loadTimePeriods(item.dt);
  } else if (item.totalTicketsNum === 0) {
    showNotify({ type: "warning", message: "该日期已无余票" });
  }
};

const setActTimePeriod = (item: any) => {
  if (item.ticketNum > 0) {
    actTimePeriod.value = item.timePeriod;
  } else {
    showNotify({ type: "warning", message: "该时段已无余票" });
  }
};

const onAdd = () => {
  if (!actDate.value) {
    showNotify({ type: "danger", message: "请选择参观日期" });
    return;
  }
  
  if (!actTimePeriod.value) {
    showNotify({ type: "danger", message: "请选择时段" });
    return;
  }
  
  const data: OrderDTO = order;
  data.visitDate = actDate.value;
  data.visitPeriod = actTimePeriod.value;
  
  // 查找选中时段的展示名称和剩余票数
  const selectedTimePeriod = timePeriod.value.find(item => item.timePeriod === actTimePeriod.value);
  if (selectedTimePeriod) {
    data.visitPeriodShow = selectedTimePeriod.timePeriodShow;
    // 保存剩余票数到ticketNum字段，供fillinfo页面用于限制人数输入
    data.ticketNum = selectedTimePeriod.ticketNum;
  }
  
  useOrderStore().setOrder(data);
  router.push("/flow/fillinfo");
};

onBeforeMount(() => {
  actTimePeriod.value = order.visitPeriod;
  actDate.value = order.visitDate;
  getCalendar();
});
</script>

<style lang="scss" scoped>
.calendar-title {
  font-size: 16px;
  line-height: 24px;
  margin: 10px;
}

.calendar-month {
  font-size: 14px;
  line-height: 24px;
  margin: 10px;
}

.calendar {
  margin-top: 10px;
  overflow: hidden;

  .week-ul {
    width: 357px;
    overflow: hidden;
    margin: 0 auto;

    li {
      float: left;
      width: 43px;
      margin: 4px;
      color: #202835;
      font-size: 14px;
      font-weight: 700;

      p {
        text-align: center;
        line-height: 24px;
        font-weight: 600;
      }
    }
  }

  .date-ul {
    width: 357px;
    overflow: hidden;
    margin: 0 auto;

    li {
      width: 43px;
      height: 50px;
      border: 1px solid #000;
      cursor: pointer;
      position: relative;
      float: left;
      margin: 4px;
      border-radius: 4px;
      transition: all 0.3s;
      display: flex;
      flex-direction: column;
      justify-content: center;

      span {
        position: absolute;
        top: 3px;
        right: 3px;
        font-size: 10px;
        color: var(--base-color);
      }

      p {
        line-height: 20px;
        text-align: center;
      }

      .p_date {
        font-size: 14px;
        color: #55555a;
      }

      .p_status {
        color: #474e63;
        font-size: 10px;
      }

      &:hover {
        border-color: var(--base-color);

        .p_date {
          color: var(--base-color);
        }

        .p_status {
          color: var(--base-color);
        }
      }

      &.forbid_click {
        background: #fff;
        pointer-events: none;
        padding-top: 7px;
        border: 1px solid #d5d5dd;

        .p_date {
          color: #d5d5dd;
        }

        .p_status {
          color: #d5d5dd;
        }
      }

      &.date_act {
        border: 0;
        background: var(--base-color);
        padding-top: 4px;

        .p_date {
          color: #fff;
        }

        .p_status {
          color: #fff;
        }
      }
    }
  }

  .time-box {
    width: 100%;
    overflow: hidden;

    p {
      color: #55555a;
      font-size: 16px;
      font-weight: 700;
      float: left;
      line-height: 24px;
      padding-left: 10px;
      padding-top: 10px;
    }

    ul {
      width: 100%;
      overflow: hidden;
      float: right;

      li {
        float: left;
        width: 105px;
        height: 50px;
        border: 1px solid #000;
        margin: 10px;
        cursor: pointer;
        border-radius: 4px;
        color: #55555a;
        font-size: 14px;
        text-align: center;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        justify-content: center;

        .time-item {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          width: 100%;
        }

        .ticket-num {
          font-size: 12px;
          color: #888;
          margin-top: 2px;
        }

        &:hover {
          border-color: var(--base-color);
          color: var(--base-color);
        }

        &.time_act {
          background: var(--base-color);
          color: #fff;
          border-color: var(--base-color);
          
          .ticket-num {
            color: #fff;
          }
        }
        
        &.forbid_click {
          background: #fff;
          pointer-events: none;
          border: 1px solid #d5d5dd;
          color: #d5d5dd;
          
          .ticket-num {
            color: #d5d5dd;
          }
        }
      }
    }
  }
}

.tip-info {
  padding: 10px;
  color: #000;
  font-size: 18px;
  line-height: 30px;

  p {
    font-size: 18px;
    font-weight: 700;
    line-height: 32px;
  }
}

.bottom-round {
  margin: 0 auto;
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  bottom: 20px;
  overflow: hidden;
  width: 300px;
  height: 40px;
  border-radius: 20px;
  display: flex;

  .bottom-btn {
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;

    &.fir {
      width: 40%;
      background-color: #e0e8fb;
      color: #7f9ccf;
    }

    &.sec {
      width: 60%;
      background-color: #225bed;
      color: #fff;
    }
  }
}
</style>
